<?php
class Helper_BSS_API
{
	static function pushZencartProductInfo($data, $wn, $api_type, $author)
	{
		set_time_limit(600);
		$host = 'api.boxintheship.com';
		$path = '/api_select_control_v1.11.9.php?on=' . Q::ini('custom_api/website_api_key') . "&wn={$wn}&apiType={$api_type}&action=products_import";
		$pre_data = 'author='. $author .'&key=YIruRgsHO.AzOosg3wFxjxVRq&content=';
		$data = $pre_data.urlencode($data);
		$fp = fsockopen($host, 80);
		fputs($fp,"POST $path HTTP/1.1\r\n");
		fputs($fp,"Host: $host\r\n");
		fputs($fp,"Content-type: application/x-www-form-urlencoded\r\n");
		fputs($fp,"Content-length: " . strlen($data) . "\r\n");
		fputs($fp, "User-Agent: MSIE\r\n");
		fputs($fp, "Connection: close\r\n\r\n");
		fputs($fp, $data);
		$buf='';
		while (!feof($fp))
		{
			$buf .= fgets($fp);
		}
		fclose($fp);
	}
	
	static function getZencartCustomerByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=get_customer_info&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=get_customer_info&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function getProductImageUrl($number)
	{
		set_time_limit(300);
		$remote_data = Product_Basic::find('number=?', $number)->asArray()->getOne();
		return json_decode($remote_data['img']);
	}
	
	static function getZencartOrderByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function getMagentoOrderByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&ukey={$website['ukey']}&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&ukey={$website['ukey']}&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function PushZencartOrderTrackingNumberByAPI($shop_id, $data)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$wn = $website['md5'];
		$api_type = md5($website['platform']);
		$service_uri = 'http://api.boxintheship.com/api_select_control_v1.11.9.php?on=' . Q::ini('custom_api/website_api_key') . "&wn={$wn}&apiType={$api_type}&action=change_orderstatus";
		$ch = curl_init();
		$timeout = 300;
		curl_setopt($ch, CURLOPT_URL, $service_uri);
		curl_setopt($ch, CURLOPT_POST, true);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt(ch, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$response = curl_exec($ch);
		curl_close($ch);
		return unserialize(base64_decode($response));
	}
	
	static function ebayAPICall($service_uri, $header, $xml, $suffix=1, $log='true', $flag='')
	{
		set_time_limit(300);
		$result = Ebay_Api_Call_Log::checkAPICallStatus();
		if ($result['ack'] == FAILURE)
		{
			return array('ack' => FAILURE, 'message' => $result['message'], 'data' => '');
		}
		$api = new DomDocument();
		$api->loadXML($xml);
		$init_log = array('api_name' => str_replace('Request', '', $api->childNodes->item(0)->nodeName));
		$log_id = Ebay_Api_Call_Log::initLog($init_log);
		$start_execute_microtime = microtime(true);
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
		curl_setopt($connection, CURLOPT_POST, 1);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($connection, CURLOPT_TIMEOUT, 200);
		$response = trim(curl_exec($connection));
		curl_close($connection);
		$execute_microtime = sprintf('%.4f', microtime(true) - $start_execute_microtime);
		if ($response)
		{
			$filename = '';
			if ($log)
			{
				$dom = new DomDocument();
		        $dom->loadXML($response);
		        $dom->formatOutput = true;
				$username = CURRENT_USER_NAME ? CURRENT_USER_NAME : 'system';
				$filename = Q::ini('custom_system/ebay_api_call_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $dom->childNodes->item(0)->nodeName . '-' . $username . '-' . $suffix . '-' . Helper_BSS_Normal::generate(5) . '.xml';
				while (file_exists($filename))
				{
					$filename = Q::ini('custom_system/ebay_api_call_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $dom->childNodes->item(0)->nodeName . '-' . $username . '-' . $suffix . '-' . Helper_BSS_Normal::generate(5) . '.xml';
				}
				file_put_contents($filename, $dom->saveXML());
			}
			$response_xml = simplexml_load_string($response);
			$completed_log = array(
				'id' => $log_id['id'],
				'status' => Q::ini('custom_flag/ebay_api_call_log_status/completed/value'),
				'execute_microtime' => $execute_microtime,
				'ack' => isset($response_xml->Ack) ? $response_xml->Ack : (isset($response_xml->ack) ? $response_xml->ack : ''),
				'message' => isset($response_xml->Errors->ShortMessage) ? (string)$response_xml->Errors->ShortMessage : (isset($response_xml->errorMessage[0]->error[0]->message[0]) ? (string)$response_xml->errorMessage[0]->error[0]->message[0] : ''),
				'filename' => str_replace(Q::ini('custom_system/ebay_api_call_log_dir'), '', $filename),
				'other_flag' => $flag
			);
			Ebay_Api_Call_Log::completedLog($completed_log);
			return array('ack' => SUCCESS, 'message' => '', 'data' => $response);
		}
		else
		{
			QDB::getConn()->execute('update ebay_api_call_log set status=\'' . Q::ini('custom_flag/ebay_api_call_log_status/completed/value') . '\', execute_microtime=\'' . $execute_microtime . '\' where id=\'' . $log_id['id'] . '\'');
			return array('ack' => FAILURE, 'message' => 'API请求返回结果异常，请稍后再试！', 'data' => '');
		}
	}
	
	static function getZencartCategories($shop)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop['id'])
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_categories_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=categories_tree", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_categories_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=categories_tree");
		}
		if ($remote_data)
		{
			file_put_contents(Q::ini('custom_system/zencart_categories_dir') . "website{$website['shop_id']}", $remote_data);
		}
		else
		{
			file_put_contents(Q::ini('custom_system/zencart_categories_dir') . "website{$website['shop_id']}", serialize(array()));
		}
	}
	
	static function getshopAnalyserData($shop_md5, $btime, $etime)
	{
		$remote_data = file_get_contents(Q::ini('custom_api/get_shop_analyser_data_api') . "website_md5={$shop_md5}&btime={$btime}&etime={$etime}");
		return unserialize($remote_data);
	}
	
	static function requestItemByNextToken($next_token, $service, $merchant_id)
	{
		$result = array('items' => '', 'next_token' => '');
		$next_item_request = new MarketplaceWebServiceOrders_Model_ListOrderItemsByNextTokenRequest();
		$next_item_request->setSellerId($merchant_id);
		$next_item_request->setNextToken($next_token);
		$next_item_response = $service->listOrderItemsByNextToken($next_item_request);
		$listOrderItemsByNextTokenResult = $next_item_response->getListOrderItemsByNextTokenResult();
		if ($listOrderItemsByNextTokenResult->isSetNextToken())
		{
			$result['next_token'] = $listOrderItemsByNextTokenResult->getNextToken();
		}
		if ($listOrderItemsByNextTokenResult->isSetOrderItems())	
		{
			$orderItems = $listOrderItemsByNextTokenResult->getOrderItems();
			$orderItemList = $orderItems->getOrderItem();
			$result['items'] = Helper_BSS_Normal::assembledAmazonItemsToArray($orderItemList);
		}
		return $result;
	}
	
	static function requestItemByAmazonAPI($amazon_order_id, $shop_id)
	{
		set_time_limit(0);
		require_once (Q::ini('custom_system/lib_dir') . 'MarketplaceWebServiceOrders/Client.php');
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)
				->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
				->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebServiceOrders_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$amazon_shop['application_name'],
				$amazon_shop['version'],
				$config
		);
		$item_request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
		$item_request->setSellerId($amazon_shop['merchant_id']);
		$item_request->setAmazonOrderId($amazon_order_id);
		$item_response = $service->listOrderItems($item_request);
		$listOrderItemsResult = $item_response->getListOrderItemsResult();
		if ($listOrderItemsResult->isSetOrderItems())
		{
			$orderItems = $listOrderItemsResult->getOrderItems();
			$orderItemList = $orderItems->getOrderItem();
			$items = Helper_BSS_Normal::assembledAmazonItemsToArray($orderItemList);
		}
		if ($listOrderItemsResult->isSetNextToken())
		{
			$next_token = $listOrderItemsResult->getNextToken();
			while ($next_token)
			{
				$result = Helper_BSS_API::requestItemByNextToken($next_token, $service, $amazon_shop['merchant_id']);
				$next_token = $result['next_token'];
				$items = array_merge($items, $result['items']);
			}
		}
		return $items;
	}
	
	static function requestListOrdersByNextToken($next_token, $shop_id)
	{
		set_time_limit(0);
		require_once (Q::ini('custom_system/lib_dir') . 'MarketplaceWebServiceOrders/Client.php');
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
			->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebServiceOrders_Client(
			$amazon_shop['access_key'],
			$amazon_shop['secret_key'],
			$amazon_shop['application_name'],
			$amazon_shop['version'],
			$config
		);
		$request = new MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
		$request->setNextToken($next_token);
 		$request->setSellerId($amazon_shop['merchant_id']);
 		$response = $service->listOrdersByNextToken($request);
		$listOrdersByNextTokenResult = $response->getListOrdersByNextTokenResult();
		if ($listOrdersByNextTokenResult->isSetOrders())
		{
			$orders = $listOrdersByNextTokenResult->getOrders();
			$orderList = $orders->getOrder();
			$sales_order = Helper_BSS_Normal::assembledAmazonOrdersToArray($orderList, $shop_id);
			if ($listOrdersByNextTokenResult->isSetNextToken())
			{
				$exists_next_token = $listOrdersByNextTokenResult->getNextToken();
				return array('orders' => $sales_order, 'next_token' => $exists_next_token);
			}
			else
			{
				return array('orders' => $sales_order, 'next_token' => '');
			}
		}
	}
	
	static function getAmazonReportRequestId($shop_ids)
	{
		set_time_limit(0);
		$amazon_shops = Shop_API_Amazon::find('shop_id in (' . implode(',', $shop_ids) . ')')->asArray()->getAll();
		foreach ($amazon_shops as $amazon_shop)
		{
			$service_url = 'https://' . $amazon_shop['mws_endpoint'];
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
			);
			$request_id = '';
			$request = new MarketplaceWebService_Model_RequestReportRequest();
			$request->setMarketplaceIdList(array('Id' => array($amazon_shop['marketplace_id'])));
			$request->setMerchant($amazon_shop['merchant_id']);
			$request->setReportType('_GET_MERCHANT_LISTINGS_DATA_BACK_COMPAT_');
			$response = $service->requestReport($request);
			if ($response->isSetRequestReportResult() && $response->getRequestReportResult()->isSetReportRequestInfo())
			{
				$reportRequestInfo = $response->getRequestReportResult()->getReportRequestInfo();
				if ($reportRequestInfo->isSetReportRequestId())
				{
					$request_id = $reportRequestInfo->getReportRequestId();
				}
        	}
        	QDB::getConn()->execute('insert into online_amazon_task (shop_id, request_id, request_time) values (' . $amazon_shop['shop_id'] . ', \'' . $request_id . '\', \'' . CURRENT_DATETIME . '\')');
		}
		return array('ack' => SUCCESS, 'message' => 'success getAmazonReportRequestId, execute time:' . sprintf('%.4f', microtime(true) - $GLOBALS['g_boot_time']) . '(secs)');
	}
	
	static function getAmazonReportListId($amazon_shops)
	{
		set_time_limit(0);
		$wrong_listing = '';
		foreach ($amazon_shops as $amazon_shop)		
		{
			$service_url = 'https://' . $amazon_shop['mws_endpoint'];
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
			);
			try
			{
				$request_list = new MarketplaceWebService_Model_GetReportListRequest();
				$request_list->setMerchant($amazon_shop['merchant_id']);
				$request_list->setMarketplace($amazon_shop['marketplace_id']);
				$request_list->setReportRequestIdList(array($amazon_shop['request_id']));
				$response_list = $service->getReportList($request_list);
				$getReportListResult = $response_list->getGetReportListResult()->getReportInfoList();
				if ($getReportListResult && $getReportListResult[0]->isSetReportId())
				{
					$report_id = $getReportListResult[0]->getReportId();
					$request_report = new MarketplaceWebService_Model_GetReportRequest();
					$request_report->setMerchant($amazon_shop['merchant_id']);
					$request_report->setMarketplace($amazon_shop['marketplace_id']);
					$request_report->setReport(@fopen('php://temp', 'rw+'));
					$request_report->setReportId($report_id);
					$response_report = $service->getReport($request_report);
					$i = 1;
					$products = array();
					if (in_array($amazon_shop['name'], array('yes_amz_us', 'yes_amz_uk', 'yes_amz_it', 'yes_amz_de', 'yes_amz_es', 'yvt_amz_uk', 'yvt_amz_de', 'yvt_amz_us')))
					{
						while (($buffer = fgets($request_report->getReport(), 10240)) !== false)
						{
						 	if ($i != 1)
						 	{
						 		if ($data = explode("\t", $buffer))
						 		{
							 		$products[] = array('sku' => trim($data[3]), 'price' => str_replace(',', '.', trim($data[4])), 'quantity' => trim($data[5]), 'open_date' => trim($data[6]), 'shop_item_id' => trim($data[22]));
						 		}
						 	}
						 	$i++;
					    }
					}
					elseif ($amazon_shop['name'] == 'yes_amz_jp')
					{
						while (($buffer = fgets($request_report->getReport(), 10240)) !== false)
						{
						 	if ($i != 1)
						 	{
						 		if ($data = explode("\t", $buffer))
						 		{
							 		$products[] = array('sku' => trim($data[2]), 'price' => trim($data[3]), 'quantity' => trim($data[4]), 'open_date' => trim($data[5]), 'shop_item_id' => trim($data[10]));
						 		}
						 	}
						 	$i++;
					    }
					}
					else
					{
						while (($buffer = fgets($request_report->getReport(), 10240)) !== false)
						{
						 	if ($i != 1)
						 	{
						 		if ($data = explode("\t", $buffer))
						 		{
							 		$products[] = array('sku' => trim($data[2]), 'price' => str_replace(',', '.', trim($data[3])), 'quantity' => trim($data[4]), 'open_date' => trim($data[5]), 'shop_item_id' => trim($data[11]));
						 		}
						 	}
						 	$i++;
					    }
					}
				    fclose($request_report->getReport());
	        		foreach ($products as $p)
			    	{
			    		if (! Online_Amazon_Product::judgeOnlineAmazonProductFormat($p['sku']))
			    		{
			    			$wrong_listing .= $p['sku'] . "\t" . $p['shop_item_id'] . "\t" . $amazon_shop['name'] . "\t\n";
			    			continue;
			    		}
			    		$old_product = Online_Amazon_Product::find('sku=? and shop_id=?', $p['sku'], $amazon_shop['shop_id'])->getOne();
			    		$status = ($p['quantity'] == 0) ? Q::ini('custom_flag/online_amazon_product_status/offsale/value') : Q::ini('custom_flag/online_amazon_product_status/onsale/value');
			    		if ($old_product['id'])
			    		{
				    		$old_product->price = $p['price'];
				    		$old_product->quantity = $p['quantity'];
				    		$old_product->update_time = CURRENT_DATETIME;
				    		$old_product->status = $status;
				    		$old_product->save();
			    		}
			    		else
			    		{
			    			$product_basic = Product_Basic::find('number=?', substr($p['sku'], 0, 6))->asArray()->getOne();
			    			$date_format = (in_array($amazon_shop['name'], array('yes_amz_us', 'yes_amz_ca', 'yvt_amz_us'))) ? 'Y-m-d H:i:s e' : (($amazon_shop['name'] == 'yes_amz_jp') ? 'Y/m/d H:i:s e' : 'd/m/Y H:i:s e');
			    			$online_amazon_product = new Online_Amazon_Product();
				    		$online_amazon_product->shop_id = $amazon_shop['shop_id'];
				    		$online_amazon_product->sku = $p['sku'];
				    		$online_amazon_product->product_basic_id = isset($product_basic['id']) ? $product_basic['id'] : '';
				    		$online_amazon_product->shop_item_id = $p['shop_item_id'];
				    		$online_amazon_product->status = $status;
				    		$online_amazon_product->price = $p['price'];
				    		$online_amazon_product->quantity = $p['quantity'];
				    		$online_amazon_product->open_time = ($p['open_date']) ? date_format(date_timezone_set(date_create_from_format($date_format, $p['open_date']), new DateTimeZone(Q::ini('l10n_default_timezone'))), 'Y-m-d H:i:s') : '';
				    		$online_amazon_product->update_time = CURRENT_DATETIME;
				    		$online_amazon_product->save();
			    		}
			    	}
			    	QDB::getConn()->execute('update online_amazon_task set report_id=' . $report_id . ', report_time=\'' . CURRENT_DATETIME . '\' where id=' . $amazon_shop['online_amazon_task_id']);
				}
				else
				{
					QDB::getConn()->execute('update online_amazon_task set notes=\'Request Report List ID is NULL\' where id=' . $amazon_shop['online_amazon_task_id']);
				}
			}
			catch (MarketplaceWebServiceOrders_Exception $ex)
			{
		        QDB::getConn()->execute('update online_amazon_task set notes=\'' . $ex->getMessage() . '\' where id=' . $amazon_shop['online_amazon_task_id']);
			}
		}
		if ($wrong_listing)
    	{
    		$wrong_listing = "错误SKU\t店铺ID\t所在店铺\t\n" . $wrong_listing;
    		$wrong_listing = iconv("UTF-8","UTF-16LE",$wrong_listing);
			$wrong_listing = "\xFF\xFE".$wrong_listing;
			$file_name = date('Y-m-d', CURRENT_TIMESTAMP) . '-' . "Amazon.xls";
			$file = file_put_contents(Q::ini('custom_system/wrong_listing_dir') . $file_name, $wrong_listing);
    	}
		return array('ack' => SUCCESS, 'message' => 'success getAmazonReportListId, execute time:' . sprintf('%.4f', microtime(true) - $GLOBALS['g_boot_time']) . '(secs)');
	}
	
	static function iEUBAPICall($service_uri, $type, $xml = '', $log='true')
	{
		$header = array(
			'version:' . Q::ini('custom_api/ieub_api_version'),
			'authenticate:' . Q::ini('custom_api/ieub_api_authenticate')
		);
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
		curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $type);
		if ($type == 'POST')
		{
			curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
		}
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		$response = trim(curl_exec($connection));
		if ($log && $response)
		{
			$username = CURRENT_USER_NAME ? CURRENT_USER_NAME : 'system';
			$filename = Q::ini('custom_system/ieub_api_call_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $username . '.xml';
			file_put_contents($filename, $response);
		}
		return $response;
	}
	
	static function ebayTemplateRsync()
	{
		$cmd = 'rsync -vzrtopg --progress --delete ' . Q::ini('custom_system/ebay_template_prodcution_for_outside_dir') . ' ebtpl@ebtpl.xftl.com::ebtpl --password-file=' . Q::ini('custom_system/ebay_template_rsync_password_file');
		exec($cmd);
	}
	
	static function AliSignature($param)
	{
		ksort($param);
		$sign = '';
		foreach ($param as $key => $val)
		{
			if ($key != '' && $val != '')
			{
				$sign .= $key . $val;
			}
		}
		$sign = strtoupper(bin2hex(hash_hmac("sha1", $sign, Q::ini('custom_api/aliexpress_secret_key'), true)));
		return $sign;
	}
	
	static function AliExpressAPICall($service_uri, $param, $need_sign, $type='POST')
	{
		if ($need_sign)
		{
			$sign = self::AliSignature($param);
			$param['_aop_signature'] = $sign;
		}
		if ($type == 'GET')
		{
			$service_uri .= '?' . http_build_query($param);
		}
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $type);
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		if ($type == 'POST')
		{
			curl_setopt($connection, CURLOPT_POSTFIELDS, http_build_query($param));
		}
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		$result = curl_exec($connection);
		curl_close($connection);
		$ret = json_decode($result, true);
		return $ret;
	}
	
	static function AutoImportAmazonOrder($shop, $begin_sales_time, $end_sales_time)
	{
		set_time_limit(0);
		$message = '';
		foreach ($shop as $s)
		{
			$service_url = 'https://' . $s['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $s['proxy_host'] ? $s['proxy_host'] : null,
				'ProxyPort' => $s['proxy_port'] ? $s['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebServiceOrders_Client(
				$s['access_key'],
				$s['secret_key'],
				$s['application_name'],
				$s['version'],
				$config
			);
			$sales_order = array();
			$channels_status = array('AFN' => array('Shipped'), 'MFN' => array('Unshipped', 'PartiallyShipped'));
			foreach ($channels_status as $k => $cs)
			{
				$request_{$k} = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
				$request_{$k}->setSellerId($s['merchant_id']);
				$orderStatuses_{$k} = new MarketplaceWebServiceOrders_Model_OrderStatusList();
				$orderStatuses_{$k}->setStatus($cs);
				$request_{$k}->setOrderStatus($orderStatuses_{$k});
				$start_time = explode(' ', $begin_sales_time);
				$end_time = explode(' ', $end_sales_time);
				$LastUpdateAfter = isset($start_time[1]) ? $begin_sales_time : $begin_sales_time . '00:00:00';
				$LastUpdateBefore = isset($end_time[1]) ? (($end_sales_time >= date('Y-m-d H:i', CURRENT_TIMESTAMP)) ? date('Y-m-d H:i:s', CURRENT_TIMESTAMP-600) : $end_sales_time) :  $end_sales_time . ' 23:59:59';
				$request_{$k}->setLastUpdatedAfter(date('c', strtotime($LastUpdateAfter)));
				$request_{$k}->setLastUpdatedBefore(date('c', strtotime($LastUpdateBefore)));
				$fullfillmentChannels_{$k} = new MarketplaceWebServiceOrders_Model_FulfillmentChannelList();
				$fullfillmentChannels_{$k}->setChannel(array($k));
				$request_{$k}->setFulfillmentChannel($fullfillmentChannels_{$k});
				$marketplaceIdList_{$k} = new MarketplaceWebServiceOrders_Model_MarketplaceIdList();
				$marketplaceIdList_{$k}->setId(array($s['marketplace_id']));
				$request_{$k}->setMarketplaceId($marketplaceIdList_{$k});
				try
				{
					$response_{$k} = $service->listOrders($request_{$k});
					$listOrdersResult_{$k} = $response_{$k}->getListOrdersResult();
					if ($listOrdersResult_{$k})
					{
						if ($listOrdersResult_{$k}->isSetOrders())
						{
							$orders_{$k} = $listOrdersResult_{$k}->getOrders();
							$orderList = $orders_{$k}->getOrder();
							$sales_order = array_merge($sales_order, Helper_BSS_Normal::assembledAmazonOrdersToArray($orderList, $s['shop_id']));
						}
						if ($listOrdersResult_{$k}->isSetNextToken()) 
						{
							$next_token = $listOrdersResult_{$k}->getNextToken();
							while ($next_token)
							{
								$result = Helper_BSS_API::requestListOrdersByNextToken($next_token, $s['shop_id']);
								$next_token = $result['next_token'];
								$sales_order = array_merge($sales_order, $result['orders']);
							}
						}
					}
				}
				catch (MarketplaceWebServiceOrders_Exception $ex)
				{
					echo("Caught Exception: " . $ex->getMessage() . "\n");
			        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
			        echo("Error Code: " . $ex->getErrorCode() . "\n");
			        echo("Error Type: " . $ex->getErrorType() . "\n");
			        echo("Request ID: " . $ex->getRequestId() . "\n");
			        echo("XML: " . $ex->getXML() . "\n");
			        echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
					sleep(65);
					continue;
				}
			}
			foreach ($sales_order as $k => $so)
			{
				$check_exists = Sales_Order::judgeImport($s['shop_id'], $so['shop_order_number']);
				if ($check_exists['ack'] == SUCCESS)
				{
					$sales_order[$k]['item'] = Helper_BSS_API::requestItemByAmazonAPI($so['shop_order_number'], $s['shop_id']);
				}
			}
			$sales_order_result = Sales_Order::import($sales_order);
			if ($sales_order_result['ack'] != SUCCESS)
			{
				$message .= $sales_order_result['message'];
			}
		}
		return array('ack' => SUCCESS, 'message' => $message);
	}
	
	/**
	 * Amazon上传数据API整合方法
	 * @param 店铺ID $shop_id
	 * @param 上传数据 $xml
	 * @param 枚举上传数据类型 $feed_type
	 */
	static function submitFeedToAmazon($shop_id, $xml, $feed_type)
	{
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'];
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
		);
		$feedHandle = @fopen('php://temp', 'rw+');
		fwrite($feedHandle, $xml);
		rewind($feedHandle);
		$parameters = array (
		  'Merchant' => $amazon_shop['merchant_id'],
		  'MarketplaceIdList' => array("Id" => array($amazon_shop['marketplace_id'])),
		  'FeedType' => $feed_type,
		  'FeedContent' => $feedHandle,
		  'PurgeAndReplace' => false,
		  'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)),
		);
		rewind($feedHandle);
		$request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters);
		$response = $service->submitFeed($request);
		if ($response->isSetSubmitFeedResult())
		{
			$feedSubmissionInfo = $response->getSubmitFeedResult()->getFeedSubmissionInfo();
			$feedSubmissionId = $feedSubmissionInfo->getFeedSubmissionId();
			file_put_contents(Q::ini('custom_system/amazon_submit_feed_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $feedSubmissionId . '-' . CURRENT_USER_NAME . '.xml', $xml);
		}
		@fclose($feedHandle);
		if (isset($feedSubmissionId))
		{
			header("Content-Type:text/html; charset=utf-8");
			echo '上传成功，查询ID为：' . $feedSubmissionId . '请到Amazon后台查询数据是否已正确处理，有问题请联系运维组同事！';
		}
	}
	
	static function wishAPICall($uri, $timeout = 300)
	{
		$response = array();
		do
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $uri);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$output = curl_exec($ch);
			curl_close($ch);
			$output = json_decode($output, true);
			foreach($output['data'] as $o)
			{
				$response[] = $o;
			}
			if (isset($output['paging']['next']) && $output['paging']['next'])
			{
				$uri = $output['paging']['next'];
			}
		} while (isset($output['paging']['next']));
		if ($response)
		{
			return array('ack' => SUCCESS, 'message' => '', 'data' => $response);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'API请求返回结果异常，请稍后再试！', 'data' => '');
		}
	}
	
	//新的接口文件
	static function getk($barcode)
	{
		$login_url = "" . $barcode;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $login_url);        //设置url
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   //设置开启重定向支持
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
		$output = curl_exec($ch);  //执行
		curl_close($ch);
		if (trim($output))
		{
			return trim($output);
		}
	}
}